package com.quyunshuo.module.home.activity.main

import android.util.Log
import androidx.lifecycle.viewModelScope
import com.quyunshuo.androidbaseframemvvm.base.mvvm.vm.BaseViewModel
import com.quyunshuo.module.home.room.database.SumDataBase
import com.quyunshuo.module.home.room.entity.PoetEntity
import com.quyunshuo.module.home.room.manager.PoetRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * 首页的VM层
 *
 * @property mRepository HomeRepository 仓库层 通过Hilt注入
 *
 * @author Qu Yunshuo
 * @since 5/25/21 5:41 PM
 */
@HiltViewModel
class HomeViewModel @Inject constructor(private val mRepository: HomeRepository) : BaseViewModel() {
    private val videoDao by lazy { SumDataBase.getInstance().poetDao() }

    private val repository = PoetRepository(videoDao)

    fun getAll(): Flow<List<PoetEntity>> = repository.allPoets

//    suspend fun getIdAndPoetList() =repository.getIdAndPoetList()

    // 使用StateFlow实现响应式数据流
    private val _poetsMap = MutableStateFlow<Map<Long, PoetEntity>>(emptyMap())
    val poetsMap: StateFlow<Map<Long, PoetEntity>> = _poetsMap.asStateFlow()

    // 初始化时加载数据
    init {
        viewModelScope.launch {
            loadPoetsMap()
        }
    }

    // 加载数据方法
    private suspend fun loadPoetsMap() {
        try {
            val map = repository.getIdAndPoetList()
            _poetsMap.value = map
        } catch (e: Exception) {
            Log.e("PoetViewModel", "加载诗人数据失败", e)
            // 处理错误，例如显示错误消息
        }
    }
}
